<template>
    <div class="box">
        <button class="sub" @click="handleSub">-</button>
        <input type="text" :value="value" class="inp" @change="handleChange">
        <button class="add" @click="handleAdd">+</button>
    </div>
</template>

<script>

export default {
  // 接收从父组件绑定的v-modelconst sub = document.querySelector('.sub')
  props: {
    value: {
      type: Number,
      default: 1 // 默认值
    }
  },
  methods: {
    handleAdd () {
      this.$emit('input', this.value + 1) // 传给父组件
    },
    handleSub () {
      if (this.value <= 1) {
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleChange (e) {
      const num = +e.target.value // 将内容转化为数值型的
      //       let num = 123.456789;
      // let strNum = num.toString();
      // let decimalPart = strNum.split('.')[1]; // 结果为 "456789"
      if (isNaN(num) || num < 1 || num > 99 || e.target.value.split('.')[1] !== undefined) { // 如果是nan或者小于1,或者小数 则回退到之前的内容
        e.target.value = this.value
      }
    }
  }
}
</script>

<style lang="less" scoped>
    .box {
        display: flex;
       width: 110px;
       .sub,
       .add {
            width: 30px;
            height: 30px;
            border: none;
            outline: none;
            background-color: azure

       }
       .inp
            {
                width: 40px;
                margin: 0px 5px;
                border: none;
                outline: none;
                text-align: center;
                background-color: azure
            };
        }
</style>
